"""
restpy/transport.py - Network transport mechanism for restpy in twisted

Copyright: Zeng Ke, superisaac.ke@gmail.com
"""
from twisted.internet import reactor
from twisted.web import xmlrpc, server
from cPickle import dumps as dumpex, loads as loadex
from base64 import decodestring, encodestring

def _dumpex(obj):
    s = dumps(obj)
    return s

def _loadex(s):
    return loads(s)

class NodeTransport(xmlrpc.XMLRPC):
    def __init__(self, node):
        xmlrpc.XMLRPC.__init__(self)
        self.node = node

    def xmlrpc_get(self, url, pickled_args):
        args, kwargs = loadex(pickled_args)
        rest = self.node.get(url)
        res= rest.get(*args, **kwargs)
        return dumpex(res)

    def xmlrpc_update(self, url, pickled_args):
        args, kwargs = loadex(pickled_args)
        rest = self.node.get(url)
        return dumpex(rest.update(*args, **kwargs))

    def xmlrpc_create(self, url, pickled_args):
        args, kwargs = loadex(pickled_args)
        rest = self.node.get(url)
        return dumpex(rest.create(*args, **kwargs))

    def xmlrpc_delete(self, url, pickled_args):
        args, kwargs = loadex(pickled_args)
        rest = self.node.get(url)
        return dumpex(rest.delete(*args, **kwargs))

def run_server(node):
    nt = NodeTransport(node)
    host, port = node.address.split(':') 
    reactor.listenTCP(int(port), server.Site(nt))
    reactor.run()

import xmlrpclib
class NodeClient:
    def __init__(self, address, url):
        self.url = url
        self.server = xmlrpclib.Server("http://%s/" % address)
    
    def get(self, *args, **kwargs):
        ps = dumpex((args, kwargs))
        return loadex(self.server.get(self.url, ps))

    def update(self, *args, **kwargs):
        ps = dumpex((args, kwargs))
        return loadex(self.server.update(self.url, ps))

    def create(self, *args, **kwargs):
        ps = dumpex((args, kwargs))
        return loadex(self.server.create(self.url, ps))

    def delete(self, *args, **kwargs):
        ps = dumpex((args, kwargs))
        return loadex(self.server.delete(self.url, ps))



    
    



